﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Keepo.Models;
using Keepo.Helpers;
using AlbumDesigner.Models.Enums;
using Keepo.Models.Services;
using AlbumDesigner.Helpers;

namespace AlbumDesigner.Controllers
{
    public class PageNotesController : Controller
    {
        private AlbumContext db = new AlbumContext();

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetPageNotes(int AlbumPageId)
        {
            //get the notes of this page
            var notes = (from n in db.PageNotes
                         where n.AlbumPageId == AlbumPageId
                         select n).ToList();

            var notesList = notes.Select(m => new PageNoteExport(m)).ToList();

            return Json(notesList);
        }

        [HttpPost]
        public ActionResult AddNote(string Text, int Receiver, int AlbumPageId)
        {
            var user = UserHelper.CurrentUser();

            EditorRoleEnum ReceiverEnum = (EditorRoleEnum) Receiver;

            //if login
            if (user != null)
            {
                var note = new PageNote();
                note.AlbumPageId = AlbumPageId;
                note.Text = Text;
                note.SentDate = DateTime.Now;

                //if the current user is a regular user (not admin)
                if (user.UserPermissionId == (int)AlbumUsers.Client)
                {
                    note.SenderId = user.UserId;
                }

                //if the receiver of this note is not admin
                if (ReceiverEnum != EditorRoleEnum.Admin)
                {
                    var page = db.AlbumPages.Find(AlbumPageId);

                    if (ReceiverEnum == EditorRoleEnum.AlbumSectionEditor)
                    {
                        note.ReceiverId = page.AlbumSection.EditorId;
                    }
                    else if (ReceiverEnum == EditorRoleEnum.AlbumEditor)
                    {
                        note.ReceiverId = page.AlbumSection.Album.EditorId;
                    }
                }

                db.PageNotes.Add(note);
                db.SaveChanges();

                PageNotesHelper.SendMailForNote(note.PageNoteId, Url);
            }

            return Json(true);
        }
    }
}
